package com.metacube.questionbank.controller;

import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;


import org.springframework.web.servlet.ModelAndView;

import com.metacube.questionbank.dao.UserDAO;
import com.metacube.questionbank.dto.UserDTO;
import com.metacube.questionbank.service.Validator;

@Controller
@RequestMapping("/login")
public class LoginController {

	@Autowired
	Validator validate;
	
	@Autowired
	UserDAO userDAO;
	
	@RequestMapping(value = "userLogin", method = RequestMethod.POST)
	public ModelAndView userLogin(@ModelAttribute UserDTO userDTO, HttpServletRequest request) {
		
		System.out.println("email : "+userDTO.geteMail());
		
		HttpSession session=request.getSession();

		if(!validate.checkUserLoginData(userDTO)) {
			
			List<UserDTO> userProfile= userDAO.checkLoginInfoFromDB(userDTO);
			
			if(userProfile.isEmpty()) {
				
				return new ModelAndView("../MetaQBank/index.jsp");
			
			} else {
				
				ModelAndView model = new ModelAndView("profile.jsp");
				model.addObject("userProfile", userProfile);
				session.setAttribute("sessionMail", userDTO.geteMail());
				session.setAttribute("sessionId", userProfile.get(0).getId());
				return model;
			}
		
		}
		return new ModelAndView("../MetaQBank/index.jsp");
	}	
}
